<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% extends 'base.html' %}

{% block title %}日志管理 - 小原焊枪选型数据库{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4 fade-in-up">
            <h1 class="display-6 fw-bold">
                <i class="bi bi-clock-history me-2"></i>
                操作日志管理
            </h1>
            <div>
                <a href="{% url 'clamps:management_dashboard' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回仪表板
                </a>
            </div>
        </div>
        
        <!-- 筛选器 -->
        <div class="card mb-4 fade-in-up">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-funnel me-2"></i>
                    日志筛选
                </h5>
            </div>
            <div class="card-body">
                <form method="get" action="{% url 'clamps:view_logs' %}" class="row g-3">
                    <div class="col-md-3">
                        <label for="action_type" class="form-label">操作类型</label>
                        <select class="form-select" id="action_type" name="action_type">
                            <option value="">全部</option>
                            <option value="login" {% if request.GET.action_type == 'login' %}selected{% endif %}>登录</option>
                            <option value="search" {% if request.GET.action_type == 'search' %}selected{% endif %}>搜索</option>
                            <option value="download" {% if request.GET.action_type == 'download' or request.GET.action_type == 'batch_download' %}selected{% endif %}>下载</option>
                            <option value="view" {% if request.GET.action_type == 'view' %}selected{% endif %}>查看</option>
                            <option value="export_data" {% if request.GET.action_type == 'export_data' %}selected{% endif %}>导出数据</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" name="username" 
                               value="{{ request.GET.username }}" placeholder="输入用户名">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="date_from" class="form-label">开始日期</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="{{ request.GET.date_from }}">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="date_to" class="form-label">结束日期</label>
                        <input type="date" class="form-control" id="date_to" name="date_to" 
                               value="{{ request.GET.date_to }}">
                    </div>
                    
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search me-2"></i>
                            筛选日志
                        </button>
                        <a href="{% url 'clamps:view_logs' %}" class="btn btn-outline-secondary ms-2">
                            <i class="bi bi-arrow-clockwise me-2"></i>
                            重置筛选
                        </a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 日志列表 -->
        <div class="card fade-in-up">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-list me-2"></i>
                    操作日志 (共 {{ total_count }} 条)
                </h5>
                <div>
                    <form method="post" action="{% url 'clamps:export_data' %}" style="display: inline;">
                        {% csrf_token %}
                        <input type="hidden" name="data_type" value="logs">
                        <!-- 保持当前筛选条件 -->
                        {% if request.GET.action_type %}
                            <input type="hidden" name="action_type" value="{{ request.GET.action_type }}">
                        {% endif %}
                        {% if request.GET.username %}
                            <input type="hidden" name="username" value="{{ request.GET.username }}">
                        {% endif %}
                        {% if request.GET.date_from %}
                            <input type="hidden" name="date_from" value="{{ request.GET.date_from }}">
                        {% endif %}
                        {% if request.GET.date_to %}
                            <input type="hidden" name="date_to" value="{{ request.GET.date_to }}">
                        {% endif %}
                        <button type="submit" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-download me-2"></i>
                            导出日志
                        </button>
                    </form>
                </div>
            </div>
            <div class="card-body p-0">
                {% if page_obj %}
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th width="15%">时间</th>
                                    <th width="12%">用户</th>
                                    <th width="10%">操作类型</th>
                                    <th width="35%">详情</th>
                                    <th width="12%">IP地址</th>
                                    <th width="16%">用户代理</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for log in page_obj %}
                                    <tr>
                                        <td>
                                            <small>{{ log.timestamp|date:"Y-m-d H:i:s" }}</small>
                                        </td>
                                        <td>
                                            {% if log.user %}
                                                <span class="badge bg-primary">{{ log.user.username }}</span>
                                            {% else %}
                                                <span class="badge bg-secondary">匿名</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if log.action_type == 'login' %}
                                                <span class="badge bg-success">
                                                    <i class="bi bi-box-arrow-in-right me-1"></i>
                                                    登录
                                                </span>
                                            {% elif log.action_type == 'search' %}
                                                <span class="badge bg-info">
                                                    <i class="bi bi-search me-1"></i>
                                                    搜索
                                                </span>
                                            {% elif log.action_type == 'download' %}
                                                <span class="badge bg-warning">
                                                    <i class="bi bi-download me-1"></i>
                                                    下载
                                                </span>
                                            {% elif log.action_type == 'batch_download' %}
                                                <span class="badge bg-warning">
                                                    <i class="bi bi-download me-1"></i>
                                                    批量下载
                                                </span>
                                            {% elif log.action_type == 'view' %}
                                                <span class="badge bg-secondary">
                                                    <i class="bi bi-eye me-1"></i>
                                                    查看
                                                </span>
                                            {% elif log.action_type == 'export_data' %}
                                                <span class="badge bg-danger">
                                                    <i class="bi bi-file-earmark-arrow-down me-1"></i>
                                                    导出数据
                                                </span>
                                            {% else %}
                                                <span class="badge bg-secondary">{{ log.action_type }}</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {% if log.details|length > 100 %}
                                                    {{ log.details|truncatechars:100 }}
                                                    <a href="#" onclick="showFullDetails({{ log.id }}, '{{ log.details|escapejs }}')" class="text-primary">
                                                        查看全部
                                                    </a>
                                                {% else %}
                                                    {{ log.details }}
                                                {% endif %}
                                            </small>
                                        </td>
                                        <td>
                                            <small class="text-muted">{{ log.ip_address|default:"--" }}</small>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                {% if log.user_agent %}
                                                    {{ log.user_agent|truncatechars:30 }}
                                                {% else %}
                                                    --
                                                {% endif %}
                                            </small>
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页 -->
                    {% if page_obj.has_other_pages %}
                        <div class="d-flex justify-content-center mt-4">
                            <nav aria-label="日志分页">
                                <ul class="pagination">
                                    {% if page_obj.has_previous %}
                                        <li class="page-item">
                                            <a class="page-link" href="?{% if request.GET.action_type %}action_type={{ request.GET.action_type }}&{% endif %}{% if request.GET.username %}username={{ request.GET.username }}&{% endif %}{% if request.GET.date_from %}date_from={{ request.GET.date_from }}&{% endif %}{% if request.GET.date_to %}date_to={{ request.GET.date_to }}&{% endif %}page={{ page_obj.previous_page_number }}">
                                                <i class="bi bi-chevron-left"></i>
                                            </a>
                                        </li>
                                    {% endif %}
                                    
                                    {% for num in page_obj.paginator.page_range %}
                                        {% if page_obj.number == num %}
                                            <li class="page-item active">
                                                <span class="page-link">{{ num }}</span>
                                            </li>
                                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                            <li class="page-item">
                                                <a class="page-link" href="?{% if request.GET.action_type %}action_type={{ request.GET.action_type }}&{% endif %}{% if request.GET.username %}username={{ request.GET.username }}&{% endif %}{% if request.GET.date_from %}date_from={{ request.GET.date_from }}&{% endif %}{% if request.GET.date_to %}date_to={{ request.GET.date_to }}&{% endif %}page={{ num }}">{{ num }}</a>
                                            </li>
                                        {% endif %}
                                    {% endfor %}
                                    
                                    {% if page_obj.has_next %}
                                        <li class="page-item">
                                            <a class="page-link" href="?{% if request.GET.action_type %}action_type={{ request.GET.action_type }}&{% endif %}{% if request.GET.username %}username={{ request.GET.username }}&{% endif %}{% if request.GET.date_from %}date_from={{ request.GET.date_from }}&{% endif %}{% if request.GET.date_to %}date_to={{ request.GET.date_to }}&{% endif %}page={{ page_obj.next_page_number }}">
                                                <i class="bi bi-chevron-right"></i>
                                            </a>
                                        </li>
                                    {% endif %}
                                </ul>
                            </nav>
                        </div>
                    {% endif %}
                {% else %}
                    <div class="text-center py-5">
                        <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                        <h4 class="text-muted mt-3">暂无日志数据</h4>
                        <p class="text-muted">请尝试调整筛选条件或稍后再试</p>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 详情模态框 -->
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailsModalLabel">
                    <i class="bi bi-info-circle me-2"></i>
                    详细信息
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="detailsContent">
                    <!-- 详细内容将通过JavaScript填充 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
    // 原有的日志相关功能
    function showFullDetails(logId, details) {
        document.getElementById('detailsContent').innerHTML = '<p><strong>日志ID:</strong> ' + logId + '</p><p><strong>详细信息:</strong></p><pre>' + details + '</pre>';
        const modal = new bootstrap.Modal(document.getElementById('detailsModal'));
        modal.show();
    }
    
    // 设置日期筛选的默认值
    document.addEventListener('DOMContentLoaded', function() {
        const dateToInput = document.getElementById('date_to');
        if (!dateToInput.value) {
            const today = new Date().toISOString().split('T')[0];
            dateToInput.value = today;
        }
        
        const dateFromInput = document.getElementById('date_from');
        if (!dateFromInput.value) {
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            dateFromInput.value = weekAgo.toISOString().split('T')[0];
        }
    });
    
    // 导出按钮点击事件
    document.querySelector('form[action*="export_data"] button[type="submit"]').addEventListener('click', function(e) {
        showToast('正在导出日志数据，请稍候...', 'info');
    });
    
    function showToast(message, type = 'info') {
        const toastHtml = `
            <div class="toast align-items-center text-white bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        let toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
            document.body.appendChild(toastContainer);
        }
        
        toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        const toast = new bootstrap.Toast(toastContainer.lastElementChild);
        toast.show();
    }
</script>
{% endblock %}
